package be.kuleuven.thesis.neo4j;

import java.io.IOException;
import java.util.ArrayList;

import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;

import be.kuleuven.thesis.parsers.MyFeatureI;
import be.kuleuven.thesis.parsers.MyFeatureList;
import be.kuleuven.thesis.parsers.MyGeneIDGFF2Reader;

public class AddGeneFeatures {
	private static Neo4jDBManager dbManager;
	private static String geneId;
	

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		dbManager = new Neo4jDBManager();
		
		
		MyFeatureList features = MyGeneIDGFF2Reader.read("/home/moni/Documents/BioinformaticsMaster/Thesis/DataITM/SNP/ReferenceFiles/LD.ALL.M2.gff");
		
		try ( Transaction tx = dbManager.getGraphDb().beginTx()) {
			for (MyFeatureI feature : features) {
				if ("CDS".equals(feature.type())) {
					geneId = feature.getAttribute("locus_tag");
					//*System.out.println(geneId);
					
					try ( Transaction tx1 = dbManager.graphDb.beginTx() )
					{
						Label label = DynamicLabel.label( "gene" );
						ResourceIterator<Node> genes = dbManager.graphDb.findNodesByLabelAndProperty( label, "locus_tag", geneId )
					            .iterator();
					    ArrayList<Node> genesNodes = new ArrayList<>();
					    while ( genes.hasNext() )
					    {
					        genesNodes.add( genes.next() );
					    }
					 
					    for ( Node node : genesNodes )
					    {
					        node.setProperty("seqId", feature.seqname().toString());
					        node.setProperty("strand", String.valueOf(feature.location().bioStrand()));
					        
					        if(feature.hasAttribute("db_xref")){
					        	ArrayList<String> db_xref  = feature.getAttributeList("db_xref");
						        int GeneDB=0;
						        for(String i : db_xref){
						        	if(i.contains("^GeneDB"))
						        		GeneDB=db_xref.indexOf(i);
						        }
					        	node.setProperty("db_xref", db_xref.get(GeneDB));
					        }
					        	
					        
					    }
					    tx1.success();
					}
							
		
				}
			}
			tx.success();
		}

	}
	
}
